package cn.sanli.manage.controller;

import cn.sanli.manage.ex.ServiceException;
import cn.sanli.manage.pojo.dto.Login.LoginUserDTO;
import cn.sanli.manage.pojo.vo.UserMessage;
import cn.sanli.manage.security.LoginPrincipal;
import cn.sanli.manage.service.UserService;
import cn.sanli.manage.web.JsonResult;
import cn.sanli.manage.web.ServiceCode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Api(tags = "管理员登录相关接口")
@Slf4j
public class UserController {

    @Resource
    public UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @ApiOperationSupport(order = 1)
    public JsonResult<String> login(@RequestBody LoginUserDTO loginUserDTO){
        log.debug("开始在controller层处理用户登录需求，用户输入的值为{}",loginUserDTO);
        if (loginUserDTO.getNum().isEmpty() || loginUserDTO.getPassword().isEmpty()){
            throw new ServiceException(ServiceCode.ERROR_DELETE,"账号密码不能为空");
        }
        String token = userService.login(loginUserDTO);
        return JsonResult.ok(token);
    }

    /**
     * 查询登录后当事人信息
     * @param loginPrincipal
     * @return
     */
    @GetMapping("/selectUser")
    @ApiOperation(value = "查询登录后当事人信息")
    @ApiOperationSupport(order = 2)
    public JsonResult<UserMessage> selectUser(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal){
        log.debug("登录后当事人信息为：{}",loginPrincipal);
        UserMessage message = userService.message(loginPrincipal.getNum());
        return JsonResult.ok(message);
    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public JsonResult<Void> logout(){
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
        return JsonResult.ok();
    }
}
